package com.derbysoft.lowcostadapter.commons.repository.impl;

import com.derbysoft.lowcostadapter.commons.model.SystemVariable;
import com.derbysoft.lowcostadapter.commons.repository.SystemVariableRepository;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("systemVariableRepository")
public class SystemVariableRepositoryImpl
        extends CommonService<SystemVariable> implements SystemVariableRepository {
    @Override
    public SystemVariable findByName(String name) {
        return load("name", name);
    }

    @Override
    public void update(String name, String value) {
        SystemVariable systemVariable = findByName(name);
        if (systemVariable == null) {
            systemVariable = new SystemVariable();
            systemVariable.setName(name);
        }
        systemVariable.setValue(value);
        super.save(systemVariable);
    }

    @Override
    public List<SystemVariable> listAll() {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SystemVariable.class).addOrder(Order.asc("name"));
        return super.find(detachedCriteria);
    }

    @Override
    public void remove(String name) {
        SystemVariable systemVariable = findByName(name);
        if (systemVariable == null) {
            throw new IllegalArgumentException("System variable name is requied");
        }
        super.delete(systemVariable);
    }

    @Override
    public String getValue(String name) {
        SystemVariable systemVariable = findByName(name);
        if (systemVariable != null) {
            return systemVariable.getValue();
        }
        return null;
    }
}
